﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
using WebAPI.Models.Database;

namespace WebAPI.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class CacheController : ControllerBase
    {
        
        private readonly Store_2022Context _db;
        [ResponseCache(Duration = 20)]
        [HttpGet]
        public DateTime Now()
        {
            return DateTime.Now;
        }
        private readonly IMemoryCache cache;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="cache"></param>
        public CacheController(IMemoryCache cache)
        {
            this.cache = cache;
        }
        [HttpGet]
        public ActionResult<string> TryGetValueCache()
        {
            if (cache.TryGetValue("UserName", out _))
            {
                return "该缓存存在";
            }
            else
            {
                return "该缓存不存在";
            }
        }
        [HttpGet]
        public ActionResult<string> GetCache()
        {
            // 写入缓存
            cache.Set("UserName", "admin");
            cache.Set("Password", "12345");

            // 读取缓存
            string userName = cache.Get<string>("UserName");
            string password = cache.Get<string>("Password");

            // 返回
            return userName + "\n" + password;
        }
        [HttpGet]
        public ActionResult<string> GetOrCreateCache()
        {
            string userName = cache.GetOrCreate("UserName", entry =>
            {
                return "admin";
            });
            string password = cache.GetOrCreate("Password", entry =>
            {
                return "12345";
            });
            return userName + "\n" + password;
        }
        [HttpGet]
        public ActionResult<string> RemoveCache()
        {
            // 写入缓存
            cache.Set("UserName", "admin");
            cache.Set("Password", "12345");

            // 删除缓存
            cache.Remove("UserName");
            cache.Remove("Password");

            // 返回
            return "缓存删除成功";
        }
        [HttpGet]
        public ActionResult<string> CacheTime1()
        {
            string msg = string.Empty;
            cache.Set("UserName", "admin");

            // 读取缓存
            for (int i = 1; i <= 5; i++)
            {
                msg += $"第{i}秒缓存值：{cache.Get<string>("UserName")}\n";
                Thread.Sleep(1000);
            }

            // 返回
            return msg;
        }
        [HttpGet]
        public ActionResult<string> CacheTime2()
        {
            string msg = string.Empty;
            cache.Set("UserName", "admin", TimeSpan.FromSeconds(3));

            // 读取缓存
            for (int i = 1; i <= 5; i++)
            {
                msg += $"第{i}秒缓存值：{cache.Get<string>("UserName")}\n";
                Thread.Sleep(1000);
            }

            // 返回
            return msg;
        }
        [HttpGet]
        public ActionResult<string> CacheTime3()
        {
            string msg = string.Empty;
            cache.Set("UserName", "admin", new MemoryCacheEntryOptions
            {
                SlidingExpiration = TimeSpan.FromSeconds(3)
            });

            // 读取缓存
            for (int i = 1; i <= 5; i++)
            {
                msg += $"第{i}秒缓存值：{cache.Get<string>("UserName")}\n";
                Thread.Sleep(1000);
            }

            // 返回
            return msg;
        }
        [HttpGet]
        public ActionResult<string> Get()
        {
            string msg = string.Empty;
            cache.Set("UserName", "admin", new MemoryCacheEntryOptions
            {
                SlidingExpiration = TimeSpan.FromSeconds(1.5),
                AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(3)
            });

            // 读取缓存
            for (int i = 1; i <= 5; i++)
            {
                msg += $"第{i}秒缓存值：{cache.Get<string>("UserName")}\n";
                Thread.Sleep(1000);
            }

            // 返回
            return msg;
        }
        [HttpGet]
        //加上认证标签 不加拿不到登录信息
        [Authorize]
        public Good GetGoodInfo(int goodId)
        {
            //查询逻辑 后端
            var good = _db.Goods.FirstOrDefault(x => x.Id == goodId);

            //使用本地缓存保存 登录用户浏览商品记录
            //userId 登录用户Id
            var userId = Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value;
            //每个人是一样key? 不一样的，每个人的浏览记录都是单独的。
            var key = "GoodViewsCache_" + userId;

            //data 数据 用户的 浏览商品记录（用户看过的商品列表）
            //商品列表 组成 （以前看过的商品列表 + 这次商品）
            //获取以前的浏览商品列表
            var beforeData = cache.Get<List<Good>>(key);
            //如果没有以前看过的商品
            if (beforeData == null)
                beforeData = new List<Good>();
            //如果beforeData==null 对象为null 无法.方法 .属性
            beforeData.Add(good);
            var data = beforeData;
            cache.Set(key, data);
            return good;

        }
    }
}
